package ch.usi.inf.pf2.editor;

import ch.usi.inf.pf2.Sheet;
import ch.usi.inf.pf2.cell.Cell;
import ch.usi.inf.pf2.cell.Converter;

/**
 * Class that defines the paste action
 * 
 * @author Lorenzo Baracchi, Ebrisa Savina Mastrodicasa
 *
 */
public class Paste extends TextManagement 
{
	private TextManagement oldAction;
	
	/**
	 * Create a Paste object
	 * @param sheet The sheet where the paste is performed
	 * @param rowIndex the row index
	 * @param columnIndex the column index
	 * @param newCell Copy or Cut action containing the new text
	 * @throws Exception
	 */
	public Paste (Sheet sheet, int rowIndex, int columnIndex, TextManagement newCell) throws Exception 
	{
		super(sheet, rowIndex, columnIndex);
		if(newCell instanceof Copy || newCell instanceof Cut)
			oldAction=newCell;
		else
			throw new Exception("The Paste can be created only from a Cut or a Copy object");
	}
	
	
	/**
	 * @return A sentence declaring the paste execute.
	 */
	public String toString ()
	{
		Converter conv = new Converter();
		conv.setCellReferenceNumbers(new int[] {this.getColumnIndex(), this.getRowIndex()});
		conv.convertToString();
		String pasteString = "Paste this content in cell " + conv.getCellReference();
		return pasteString;
	}

	
	/**
     * Change the text into a cell by pasting something else
     * and store the old one into oldText.
     */
	@Override
	public void evaluate () 
	{
		Cell c=sheet.getCell(getColumnIndex(), getRowIndex());
		setOldText(c.getContent().toString());
		setNewText(oldAction.getOldText());
		setOldColor(c.getColor());
		setNewColor(oldAction.getOldColor());
		setOldBorder(c.getBorderType());
		setNewBorder(oldAction.getOldBorder());
		sheet.insertDataAtCell(getNewText(), getColumnIndex(), getRowIndex());
		c.setColor(getNewColor());
		c.setBorderType(getNewBorder());
		System.out.println("Paste evaluate: "+getNewText());
	}
	
	
	/**
	 * @return true if the object is an instance of Paste.
	 */
	public boolean equals (Object o)
	{
		if(o instanceof Paste)
			return super.equals(o) && oldAction.equals(((Paste)o).getOldAction()); 
		else
			return false;
	}
	
	
	/**
	 * @return The action before the just executed action.
	 */
	public TextManagement getOldAction ()
	{
		return oldAction;
	}

	
	/**
     * Undo the previous pasting of a text.
     */
	@Override
	public void restore () 
	{
	    Cell c=sheet.getCell(getColumnIndex(), getRowIndex());
	    sheet.insertDataAtCell(getOldText(), getColumnIndex(), getRowIndex());
	    c.setColor(getOldColor());
	    c.setBorderType(getOldBorder());
	}
}
